<template>
  <div class="cart-item">
      <span class="serial">{{ index + 1 }}</span>
      <span class="name">{{ product.name }}</span>
      <span class="price">{{ product.price }}</span>
      <span class="number">
          <!-- 监听当前组件中的原生事件 -->
          <button type="button" @click="reduce(product.id)">-</button>
          <!-- 监听事件调用函数，可以通过 $event 引用当前事件对象 -->
          <input type="text" :value="product.number" @input="handle( $event , product.id )">
          <button type="button" @click="increase(product.id)">+</button>
      </span>
      <span class="subtotal">{{ product.price * product.number }}</span>
      <span class="operation">
          <button type="button">删除</button>
      </span>
  </div>
</template>

<script>
// 导出单文件组件
export default {
    name: 'CartItem',
    props: [ 'index' , 'product' ] ,
    emits: [ 'product:reduce' , 'product:increase' , 'product:change' ] ,
    methods : {
        reduce(pid){
            console.log( `减少${pid}商品数量` );
            // 触发自定义事件
            this.$emit( 'product:reduce' , pid );
        },
        increase( pid ){
            console.log( `增加${pid}商品数量` );
            // 触发自定义事件
            this.$emit( 'product:increase' , pid );
        },
        handle( event , pid){
            let n = event.target.value ;
            console.log( n , pid );
            console.log( !isNaN( n ) );
            // 注意这里有感叹号
            if( !isNaN( n ) ) {
                // 触发自定义事件
                this.$emit( 'product:change' , { id: pid , number: parseInt(n) } );
            }
        }
    }
}
</script>

<style scoped>
.cart-item {
    display: flex ;
    margin: 15px ;
    border: 1px solid #dedede ;
}

.serial ,
.price ,
.subtotal {
    flex-basis: 100px ;
    text-align: center ;
}

.name {
    flex-basis: 300px ;
}

.number {
    flex-basis: 150px ;
    text-align: center ;
}

.number input[type=text] {
    text-align: center ;
    width: 50px ;
    outline: none ;
}
</style>